import { Request, Response, Router } from "express";
import { CustomResponse } from "../middleware/error";
import User from "../db/models/user";
import { Op, Sequelize } from "sequelize";
import { EROFS } from "constants";
import { sendChar } from "../utils/sendEvent";

const testRouter = Router();

testRouter.post("/token", (req: Request, res: CustomResponse) => {
  res.cookie("token", "zheshitokendezhi", {
    maxAge: 60 * 60 * 1000,
    httpOnly: true, // 禁止客户端通过JS脚本获取cookie
    domain: "localhost",
    path: "/",
    signed: true,
  });
  res.header("Authorization", "Bearer zheyibanshizhenduiyidongduandelingpai");
  const headers = req.headers;
  const cookies = req.headers.cookie;
  console.log(typeof cookies);
  res.send({
    cookies,
  });
});

testRouter.post("/mime", (req: Request, res: Response) => {
  console.log(req);
  res.send({
    status: "Hello",
  });
});
/**
 * JSONP 跨域请求
 */
testRouter.get("/jsonp", async (req: Request, res: Response) => {
  const users = await User.findAll({
    where: {
      id: {
        [Op.lt]: 100,
      },
    },
  });
  const json = JSON.stringify({
    users,
    code: 200,
    msg: "success",
  });
  const script = `callback(${json})`; // callback函数需要在前端引入的JS文件声明
  res.header("Content-Type", "application/javascript").send(script);
});

/**
 * cors 跨域
 */
testRouter.get("/cors", (req: Request, res: Response) => {
  // res.header('Access-Control-Allow-Origin', '*')
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.send({
    status: 200,
    msg: "cors success",
  });
});


export default testRouter;